package cn.wj.school.app.net.client.handler;

import cn.wj.school.common.dto.PingReq;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @Author: yueding
 * @Description: 客户端4秒没有写操作发送心跳
 * @Date: Created in 14:39 2018/12/28
 * @Modified By: yueding Copyright(c) cai-inc.com
 */
@ChannelHandler.Sharable
public class ConnectorIdleStateHandler extends ChannelInboundHandlerAdapter {

    /**
     * 事件触发器,当channel没有数据传输的时候发送心跳
     *
     * @param ctx
     * @param evt
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {
                // write heartbeat to server
                PingReq pingReq = new PingReq();
                pingReq.setMessage("Heartbeat");
                ctx.writeAndFlush(pingReq);
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
